const {MUtils} = require("../MUtils");
const {GameListResp, GameOddsResp, GameResp} = require("../../model/GameListResp");
const {PlatformUtil} = require("../PlatformUtil");

/**
 * 平博数据解析
 */
class PbDataHandler {
    /**
     * 版本号管理
     * @type {{}}
     */
    static VERSION = {};

    /**
     * 保存版本号
     *
     * @param k
     * @param v
     */
    static setVersion(k, v) {
        PbDataHandler.VERSION[k] = v;
    }

    /**
     * 获取版本号
     *
     * @param k
     * @return {number}
     */
    static getVersion(k) {
        let v = PbDataHandler.VERSION[k];
        if (v === null) {
            v = 0;
        }
        return v;
    }

    /**
     * 转换赛事列表
     *
     * @param resp      响应报文
     * @param isLive    是否滚球
     * @return {GameListResp}
     */
    static parseGameList(resp, isLive) {
        const gameListResp = new GameListResp();
        if (resp == null) {
            return gameListResp;
        }
        if (isLive) {
            const l = resp['l'];
            if (l == null || l[0] == null || l[0][2] == null) {
                return gameListResp;
            }
            return parseGameList(l);
        } else {
            const n = resp['n'];
            if (n == null || n[0] == null || n[0][2] == null) {
                return gameListResp;
            }
            return parseGameList(n);
        }
    }


    /**
     * 转换赛事列表
     *
     * @param gameId
     * @param teamTypes
     * @param oddsArr
     * @return {[]}
     */
    static parseGameDetail(gameId, teamTypes, oddsArr) {
        if (oddsArr == null || oddsArr.length === 0) {
            return [];
        }
        // 赛节索引 0-全场，1-上半场
        let oddsList = [];
        for (let i = 0; i <= 1; i++) {
            const sectionData = oddsArr[i];
            const section = i;//赛节
            if (sectionData == null || sectionData.length === 0) {
                continue;
            }
            // 模式 0-让分，1-大小
            for (let j = 0; j <= 1; j++) {
                const modeData = sectionData[j];
                if (modeData == null || modeData.length === 0) {
                    continue;
                }
                let mode;//模式 1-让分，2-大小
                if (j === 0) {
                    mode = 1;
                } else if (j === 1) {
                    mode = 2;
                }
                for (let k = 0; k < modeData.length; k++) {
                    const m = modeData[k];
                    const rowData = getRowData(gameId, teamTypes, m, section, mode);
                    if (rowData == null) {
                        continue;
                    }
                    for (let l = 0; l < rowData.length; l++) {
                        oddsList.push(rowData[l]);
                    }
                }
            }
        }
        return oddsList;
    }

    /**
     * 解析当前比分
     *
     * @param scores
     * @return {{as, hs}}
     */
    static parseGameScore(scores) {
        let hs, as;
        if (scores == null) {
            return {hs, as};
        }
        hs = scores[0];
        as = scores[1];
        return {hs, as};
    }

}

/**
 * 转换赛事列表
 *
 * @param data
 * @return {GameListResp}
 */
function parseGameList(data) {
    // 解析赛事列表
    const list = data[0][2];
    let gameList = [];
    for (let i = 0; i < list.length; i++) {
        const item = list[i];
        // 所属联赛
        const groupId = item[0];
        const groupNameCn = item[1];
        // const groupNameEn = item[4];
        const games = item[2];
        for (let j = 0; j < games.length; j++) {
            const detail = games[j];
            const gameId = detail[0];//比赛id
            const homeTeamCn = detail[1];
            const awayTeamCn = detail[2];
            // const homeTeamEn = detail[24];
            // const awayTeamEn = detail[25];
            const startDate = getStartDate(detail[4]);//开赛时间
            const stopFlag = detail[17];//判断是否停盘,H-表示停盘
            const isStop = (stopFlag === 'H');// 是否停盘，H-是
            const teamTypes = detail[11];//队伍类型
            const oddsList = PbDataHandler.parseGameDetail(gameId, teamTypes, detail[8]);
            const {hs, as} = PbDataHandler.parseGameScore(detail[9]);
            let gameTime = '';
            const gameSection = detail[16];
            if (MUtils.isNotEmpty(detail[15])) {
                let gameMin = detail[15].replace('\'', '')
                if (PlatformUtil.equals(gameSection, '2H')) {
                    gameMin = 45 + eval(gameMin);
                }
                gameTime = gameMin + ':00';
            }
            const gameResp = new GameResp(groupId, groupNameCn, null, gameId, gameTime, gameSection, homeTeamCn, null, hs, awayTeamCn, null, as, isStop, oddsList, startDate);
            gameList.push(gameResp);
        }
    }

    const gameListResp = new GameListResp();
    gameListResp.setGameList(gameList, PbDataHandler.VERSION);
    return gameListResp;
}

/**
 * 获取开始时间
 *
 * @param timestamp
 * @return {string}
 */
function getStartDate(timestamp) {
    if (timestamp == null) {
        return '';
    }
    const dateJson = MUtils.getTimeJson(timestamp, null);
    return `${dateJson.year}-${dateJson.month}-${dateJson.day} ${dateJson.hour}:${dateJson.minute}`;
}

/**
 * 获取行数据
 *
 * @param gameId
 * @param teamTypes
 * @param item      单个盘口数据
 * @param section   赛节
 * @param mode      模式
 */
function getRowData(gameId, teamTypes, item, section, mode) {
    if (item == null) {
        return null;
    }
    let rowData = [];
    for (let i = 0; i < 2; i++) {
        // 第1列-选项1,第2列-选项2
        const column = getOption(gameId, teamTypes, item, section, mode, i);
        rowData.push(column);
    }
    return rowData;
}

/**
 * 获取选项
 *
 * @param gameId
 * @param teamTypes
 * @param item          单盘口数据
 * @param section       赛节
 * @param mode          模式
 * @param column        列标
 */
function getOption(gameId, teamTypes, item, section, mode, column) {
    let odds;//赔率
    let key = '';//关键词
    let extra = '';//分值
    let desc = '';//描述
    if (mode === 1) {
        // 让分盘
        if (column === 0) {
            extra = item[1];
            odds = item[3];
            key = '主';
        } else {
            extra = item[0];
            odds = item[4];
            key = '客';
        }
        if (parseFloat(extra) > 0) {
            extra = '+' + extra;
        } else {
            extra = extra + '';
        }
    } else if (mode === 2) {
        //总得分
        extra = item[1];
        if (column === 0) {
            odds = item[2];
            key = '大';
        } else {
            odds = item[3];
            key = '小';
        }
    }

    // 大小盘
    // gameId | 0-赛局/1-上半场/2-下半场/3-第一节/4-第二节/5-第三节/6-第四节 | 3-大小盘 | [大小,大是3，小是4] | 1 | 分数值
    // 让分盘
    // gameId | 0-赛局/1-上半场/2-下半场/3-第一节/4-第二节/5-第三节/6-第四节 | 2-让分盘 | 第一个选项0，第二个选项1 | 1 | 分数值
    // 独赢
    // gameId | 0-赛局/1-上半场/2-下半场/3-第一节/4-第二节/5-第三节/6-第四节 | 1-独赢 | 第一个选项0，第二个选项1 | 0 | 0
    let itemId;
    let i3;
    let i4;
    let i5;
    let i6;
    if (mode === 1) {//让分盘
        itemId = item[7];
        i3 = 2;
        i4 = (column === 1 ? 1 : 0);
        i5 = 1;
        i6 = extra;
    } else if (mode === 2) {//大小盘
        itemId = item[4];
        i3 = 3;
        i4 = (column === 1 ? 4 : 3);
        i5 = 1;
        i6 = extra;
    }
    let oddsId = `${gameId}|${section}|${i3}|${i4}|${i5}|${i6}`;

    // itemId | oddsId | teamType
    let teamType;
    if (column === 1) {
        teamType = teamTypes[0];
    } else {
        teamType = teamTypes[1];
    }
    let selectionId = `${itemId}|${oddsId}|${teamType}`;
    const betJson = buildBetJson(oddsId, selectionId);//选择投注单所需要的数据
    desc = PlatformUtil.getExtraDesc(mode, extra);
    return new GameOddsResp(section, mode, null, odds, desc, key, extra, betJson);
}

/**
 * 构建选择注单数据
 *
 * @return {{oddsSelections: [{oddsFormat: number, oddsSelectionsType: string, oddsId: *, selectionId: *}]}}
 */
function buildBetJson(oddsId, selectionId) {
    return {
        "oddsSelections": [
            {
                "oddsFormat": 1,//1-欧式赔率，2-港式赔率
                "oddsId": oddsId,
                "oddsSelectionsType": "NORMAL",
                "selectionId": selectionId
            }
        ]
    };
}


module.exports = {
    PbDataHandler
};